<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogRequestInfoMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $url = $request->url();
        $method = $request->method();
        $requestId = $request->header('X-Request-ID') ?? $this->generateLogId();

        // 设置日志上下文，后续所有Log调用自动包含log_id
        Log::withContext(['requestId' => $requestId]);

        Log::notice($method,['url'=>$url]);
        
        return $next($request);
    }

    /**
     * 生成日志ID
     *
     * @return string
     */
    private function generateLogId(): string
    {
        return (string) mt_rand(100000000, 999999999);
    }
}